// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database();
const _ = db.command;
const $ = db.command.aggregate
const gameid = '54ad1eea6230accc1662c4fb436fb2cc'
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const gamedata = event.gamedata
  let _openid = wxContext.OPENID
  let progame = await db.collection('gamejf').doc(gameid).get()
  let remainjf = progame.data.value
  let time = new Date().getTime()
  if (remainjf == 0) {
    return {
      status: 0,
      message: `《${progame.data.name}》积分耗尽`,
      remainjf
    }
  }
  let taskUpUserjf = []
  const lastremainjf = remainjf
  //先扣除最后两名选手的积分
  let pro78 = await db.collection('user').where({
    _openid: _.in([gamedata[6]._openid, gamedata[7]._openid])
  }).field({
    _openid: true,
    jf: true,
    jonnerName: true
  }).get()
  for (let item of pro78.data) {
    const {
      _id,
      _openid,
      jf
    } = item
    if (jf > 0) {
      if (_openid == gamedata[6]._openid) {
        remainjf += 1
        let pro = db.collection('user').doc(_id).update({
          data: {
            jf: _.inc(-1)
          }
        })
        taskUpUserjf.push(pro)
      }
      if (_openid == gamedata[7]._openid) {
        let yj = jf - 2 >= 0 ? 2 : jf
        remainjf += yj
        let pro = db.collection('user').doc(_id).update({
          data: {
            jf: _.inc(-yj)
          }
        })
        taskUpUserjf.push(pro)
      }
    }
  }

  //给第一名发积分
  let giveFirstJf = remainjf < 4 ? remainjf : 4
  remainjf -= giveFirstJf
  let pro1 = db.collection('user').doc(gamedata[0]._id).update({
    data: {
      jf: _.inc(giveFirstJf)
    }
  })
  taskUpUserjf.push(pro1)

  if (remainjf > 0) {
    //给第二名发积分
    let second = remainjf < 2 ? remainjf : 2
    remainjf -= second
    let pro2 = db.collection('user').doc(gamedata[1]._id).update({
      data: {
        jf: _.inc(second)
      }
    })
    taskUpUserjf.push(pro2)

    if (remainjf > 0) {
      //给第三名发积分
      remainjf -= 1
      let pro3 = db.collection('user').doc(gamedata[2]._id).update({
        data: {
          jf: _.inc(1)
        }
      })
      taskUpUserjf.push(pro3)
    }
  }
  let resupuser = await Promise.all(taskUpUserjf)
  let upUserNum = 0
  for (let item of resupuser) {
    if (item.stats.updated == 1) upUserNum++;
  }

  //更新积分池
  let proupjfc = await db.collection('gamejf').doc(gameid).update({
    data: {
      value: remainjf
    }
  })

  //上传本局游戏到game表
  let proaddhs = await db.collection('gamehistory').add({
    data: {
      _openid,
      rankList: gamedata.map(item => item._openid),
      time
    }
  })

  //更新报名用户的hstotry字段
  let taskUpUserhs=[]
  for(let j =0;j<8;j++){
    let item=gamedata[j]
    let prohs=db.collection('user').doc(item._id).update({
      data:{
        history:_.push(j+1)
      }
    })
    taskUpUserhs.push(prohs)
  }
  await Promise.all(taskUpUserhs)  

  if (upUserNum && proupjfc.stats.updated == 1 && proaddhs._id) {
    return {
      status: 1,
      message:`${upUserNum}个选手积分更新,消耗积分${lastremainjf-remainjf},剩余总积分${remainjf}`,
      xhjf:lastremainjf-remainjf,
      remainjf
    }
  }
  else{
    return{
      status:0,
      message:'上传出现错误'
    }
  }

}